#include <shell.h>
#include <string.h>
#include <screen.h>

static fs_node_t * tmpcurnode = 0;

fs_node_t * FindParentDir (char * name)
{
	static struct dirent *node = 0;
	int i = 0;
	dprintf ("[FindParentDir] tmpcurnode->name = %s, fs_root->name = %s...\n",name, GetRootFS ()->name);
	if (!strcmp(name, GetRootFS ()->name))
		return NULL;
	while ((node = readdir_fs(tmpcurnode, i)) != 0)
	{
		fs_node_t *tmpfsnode = finddir_fs(tmpcurnode, node->name);
		if ((tmpfsnode->flags&0x7) == FS_DIRECTORY)
		{
			dprintf ("[FindParentDir] name = %s, tmpfsnode->name = %s...\n",name, tmpfsnode->name);
			if (!strcmp (name,tmpfsnode->name))
				return tmpcurnode;
			fs_node_t * tmpnode = tmpcurnode;
			tmpcurnode = tmpfsnode;
			fs_node_t * tmp = FindParentDir (name);
			if (tmp)
				return tmp;
			tmpcurnode = tmpnode;
		}
		i++;
	}
	return NULL;
}
void cd (char * param)
{
	fs_node_t *fsnode = finddir_fs(GetCurrentNodeDir(), param);
	if ((fsnode->flags&0x7) == FS_DIRECTORY)
	{
		char * dir  = GetCurrentDir();
		strcat (dir,param);
		strcat (dir,"/");
		SetCurrentDir (dir);
		//strcpy(currentdir,(char*)param);
		SetCurrentNodeDir (fsnode);
	}
	else
	{
		if (!strcmp(param,"."));
		else if (!strcmp(param,".."))
		{
			tmpcurnode = GetRootFS();
			dprintf ("[cd] tmpcurnode->name = %s...\n",tmpcurnode->name);
			fs_node_t *parent = FindParentDir (GetCurrentNodeDir()->name);
			if (parent)
			{
				SetCurrentNodeDir(parent);
				char * path = GetCurrentDir ();
				char * newpath = strsep(&path,GetCurrentNodeDir()->name);
				strcat (newpath,"/");
				SetCurrentDir (newpath);
			}
		}
		else if (!strcmp(param,"/"))
		{
			SetCurrentNodeDir(GetRootFS ());
			SetCurrentDir ("/");
		}
		else
			kprintf("Invalid directory. Type 'ls' for list.\n");
	}
}
